<?php
session_start();
require 'config.php'; // 确保config.php文件中包含了数据库连接代码

// 检测用户是否已经登录
if (isset($_POST['action']) && $_POST['action'] === 'check_../login') {
    if (isset($_SESSION['username'])) {
        echo json_encode(['status' => 'already_logged_in', 'message' => '您已经登录，请不要重复登录。']);
    } else {
        echo json_encode(['status' => 'not_logged_in', 'message' => '您尚未登录。']);
    }
    exit();
}

// 如果用户已经登录，直接返回提示信息
if (isset($_SESSION['username'])) {
    echo json_encode(['status' => 'already_logged_in', 'name' => $_SESSION['username']]);
    exit();
}

// 检查是否是POST请求
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    if (empty($username) || empty($password)) {
        echo json_encode(['status' => 'error', 'message' => '用户名和密码不能为空。']);
        exit();
    }

    // 查询用户信息
    $stmt = $conn->prepare("SELECT * FROM admin WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        // 使用MD5验证密码
        if (md5($password) === $user['password']) {
            $_SESSION['username'] = $username;
            echo json_encode(['status' => 'success']);
        } else {
            echo json_encode(['status' => 'error', 'message' => '密码错误。']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => '用户名不存在。']);
    }
    $stmt->close();
} else {
    echo json_encode(['status' => 'error', 'message' => '无效请求']);
}
?>
